package edu.upf.grupoe.p2ppicture.SearchEngine.implementations;

import edu.upf.grupoe.p2ppicture.SearchEngine.interfaces.Constants;
import edu.upf.grupoe.p2ppicture.SearchEngine.interfaces.Listener;
import edu.upf.grupoe.p2ppicture.Transfer.Implementations.TransferImpl;
import java.io.InvalidClassException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
/**
 * This class represents an income message Listener
 */
public final class ListenerImpl implements PacketListener, Listener, Constants{


    private InstantMessageImpl IM = null;

    private GenericMessageImpl msg = null;
    
    private GenericMessageImpl msgNotify = null;

    private static TransferImpl transfer = null;



    private static Log logger = LogFactory.getLog("Main");
/**
 * This method decides what to do with an incoming message when it appears in the Connection packet collector.
 * @param packet Packet
 */
    @Override
    public void processPacket(Packet packet) {
        if(packet.getProperty("SearchProfile") instanceof SearchProfileImpl){
            try {
                logger.info("Listener process Packet has detected a SP");
                IM.offerContent(packet,msg);
            } catch (XMPPException ex) {
                if(logger.isDebugEnabled()){
                    logger.error(ex.getMessage());
                }
            } catch (InvalidClassException ex) {
                if(logger.isDebugEnabled()){
                    logger.error(ex.getMessage());
                }
            }
        }
        else if(packet.getProperty("SearchResult") instanceof SearchResultImpl){
            try {
                logger.info("SR received");
                IM.getContent(packet, msg);
            } catch (XMPPException ex) {
                if(logger.isDebugEnabled()){
                    logger.error(ex.getMessage());
                }
            } catch (InvalidClassException ex) {
                if(logger.isDebugEnabled()){
                    logger.error(ex.getMessage());
                }
            }
        }
        else if(packet.getProperty("UserContent") instanceof UserContentImpl){
            logger.info("UC received");           
            IM.getRequest(packet);            
        }
        else{
           logger.info("others");
        }
    }
    /**
     * ListenerImpl Constructor
     * @param IM InstantMessageImpl
     */
    public ListenerImpl(InstantMessageImpl IM) {
        this.IM = IM;
        this.transfer = new TransferImpl(this.IM);
    }
    
    public TransferImpl getTransfer(){
        return transfer;
    }

    public GenericMessageImpl getmsgNotify(){
        return msgNotify;
    }
}
